﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows.Data;
#if !SILVERLIGHT
using UIT.WPF.Converters;

namespace UIT.WPF.Renderers
#else
using UIT.Silverlight.Converters;

namespace UIT.Silverlight.Renderers
#endif
{
	class ControlControlRenderer :
#if !SILVERLIGHT
        WpfRenderer<Controls.IDrawableControl, Control>
#else
		SlRenderer<Controls.IDrawableControl, Control>
#endif
	{
		public ControlControlRenderer(Control control)
		{
			Result = control;
		}

		public override void Render(Controls.IDrawableControl control)
		{
			if (Result == null)
				return;


#if !SILVERLIGHT
			Result.SetBinding(Control.BackgroundProperty, new Binding("Style.Background")
			{
				Converter = new BrushConverter(GetInStyle<System.Windows.Media.Brush>(Control.BackgroundProperty))
			});
#endif
		}

		private T GetInStyle<T>(System.Windows.DependencyProperty dependencyProperty)
			where T : class
		{
			return GetInStyle(dependencyProperty) as T;
		}

		private object GetInStyle(System.Windows.DependencyProperty dependencyProperty)
		{
			System.Windows.Style style = Result.Style;
#if !SILVERLIGHT
			if (style == null && Result != null)
				style = (System.Windows.Style)Control.StyleProperty.GetMetadata(Result.GetType()).DefaultValue;
			if (style == null)
				style = (System.Windows.Style)Application.Current.TryFindResource(Result.GetType());
#endif
			if (style == null)
				return null;
			return GetInStyle(style, dependencyProperty);
		}

		private object GetInStyle(System.Windows.Style style, System.Windows.DependencyProperty dependencyProperty)
		{
			if (style == null)
				return null;
			System.Windows.Setter s = style.Setters.OfType<System.Windows.Setter>().FirstOrDefault(setter => setter.Property == dependencyProperty);
			if (s == null)
				return GetInStyle(style.BasedOn, dependencyProperty);
			return s.Value;
		}

	}
}
